<?php

// 每天充值统计控制器

namespace app\api\controller;

use app\api\controller\Base;
use think\Db;

class DayRecharge extends Base
{

    /**
     * 每天统计一次充值
     */
    public function dayRecharge()
    {

        try {
            // 只允许命令行访问
            if (PHP_SAPI != 'cli') {
                return ['code' => 999, 'msg' => '404'];
            }

            debug('begin');

            // 设置多少秒执行一次（默认一天）
            $interval_time = 50000;

            // 统计时间（今天跑昨天的数据）
            $query_time = date('Y-m-d');
            $statistics_date = date('Y-m-d', (strtotime($query_time) - 3600 * 24 * 1));

            $map = [];
            Db::name('payment_merchant_config')
                ->where($map)
                ->chunk(100, function ($all) use ($statistics_date, $interval_time) {
                    foreach ($all as $single) {

                        $data = [];                       // 商户金额来源统计表数据
                        $payment_type_cash_count = [];    // 支付类型金额和数量json格式
                        $cash_table = [];                 // 商户钱包表数据
                        $merchant_balance_cash = 0;       // 结算金额
                        $all_cashs = 0;                   // 创建订单金额
                        $finish_cashs = 0;                // 完成订单金额
                        $all_cash_counts = 0;             // 创建订单数量
                        $finish_cash_counts = 0;          // 完成订单数量
                        $all_app_id_array = [];           // 记录充值的应用ID
                        $app_id = [];                     // 记录充值的应用ID对应金额
                        $balance_cash_array = [];         // 根据支付类型，统计对应的费率金额
                        $app_id_all_cashs = 0;            // 应用ID对应金额
                        $app_id_all_counts = 0;           // 应用ID对应数量
                        $app_id_finish_cashs = 0;         // 应用ID对应完成金额
                        $app_id_finish_counts = 0;        // 应用ID对应完成数量
                        $type_all_cashs = 0;              // 支付类型对应金额
                        $type_all_counts = 0;             // 支付类型对应数量
                        $type_finish_cashs = 0;           // 支付类型对应完成金额
                        $type_finish_counts = 0;          // 支付类型对应完成数量
                        // 存在跳过
                        $exist_recharge_cash_source = Db::name('payment_recharge_cash_source')
                            ->where(['merchant_id' => $single['id']])
                            ->whereTime('dates', 'between', ["{$statistics_date} 00:00:00", "{$statistics_date} 23:59:59"])
                            ->find();

                        if (!$exist_recharge_cash_source) {

                            // 商户对应支付类型费率
                            $payment_type_rate_array = json_decode($single['payment_type_rate'], true);

                            if (is_array($payment_type_rate_array)) {

                                $temp_map = [];
                                // 用支付完成时间统计，不会掉单后，第二天处理钱少
                                $temp_map[] = ['update_time', ['>=', strtotime($statistics_date)], ['<', strtotime($statistics_date) + 86400]];

                                $temp_map[] = ['merchant_id', '=', $single['id']];

                                // 创建订单数量
                                $all_cash_counts = Db::name('payment_order')
                                    ->where($temp_map)
                                    ->count();

                                // 完成订单数量
                                $finish_cash_counts = Db::name('payment_order')
                                    ->where($temp_map)
                                    ->where(['status' => 2])
                                    ->count();

                                // 创建订单金额
                                $all_cashs = Db::name('payment_order')
                                    ->where($temp_map)
                                    ->sum('cash');

                                // 完成订单金额
                                $finish_cashs = Db::name('payment_order')
                                    ->where($temp_map)
                                    ->where(['status' => 2])
                                    ->sum('cash');

                                // 记录充值的应用ID
                                $all_app_id_array = Db::name('payment_order')
                                    ->where($temp_map)
                                    ->distinct(true)
                                    ->column('app_id');

                                if ($all_app_id_array) {
                                    foreach ($all_app_id_array as $app_id_value) {

                                        $app_id_all_counts = Db::name('payment_order')
                                            ->where($temp_map)
                                            ->where(['app_id' => $app_id_value])
                                            ->count();

                                        $app_id_finish_counts = Db::name('payment_order')
                                            ->where($temp_map)
                                            ->where(['app_id' => $app_id_value])
                                            ->where(['status' => 2])
                                            ->count();

                                        $app_id_all_cashs = Db::name('payment_order')
                                            ->where($temp_map)
                                            ->where(['app_id' => $app_id_value])
                                            ->sum('cash');

                                        $app_id_finish_cashs = Db::name('payment_order')
                                            ->where($temp_map)
                                            ->where(['app_id' => $app_id_value])
                                            ->where(['status' => 2])
                                            ->sum('cash');

                                        $app_id[$app_id_value]['all']['cash'] = $app_id_all_cashs ? $app_id_all_cashs / 100 : 0;
                                        $app_id[$app_id_value]['all']['count'] = $app_id_all_counts;
                                        $app_id[$app_id_value]['finish']['cash'] = $app_id_finish_cashs ? $app_id_finish_cashs / 100 : 0;
                                        $app_id[$app_id_value]['finish']['count'] = $app_id_finish_counts;
                                    }
                                }

                                // 循环支付类型对应类型费率
                                foreach ($payment_type_rate_array as $type_key => $type_value) {

                                    // 支付类型对应创建数量
                                    $type_all_counts = Db::name('payment_order')
                                        ->where($temp_map)
                                        ->where(['type' => $type_key])
                                        ->count();

                                    // 支付类型对应完成数量
                                    $type_finish_counts = Db::name('payment_order')
                                        ->where($temp_map)
                                        ->where(['type' => $type_key])
                                        ->where(['status' => 2])
                                        ->count();

                                    // 支付类型对应创建金额
                                    $type_all_cashs = Db::name('payment_order')
                                        ->where($temp_map)
                                        ->where(['type' => $type_key])
                                        ->sum('cash');

                                    // 支付类型对应完成金额
                                    $type_finish_cashs = Db::name('payment_order')
                                        ->where($temp_map)
                                        ->where(['type' => $type_key])
                                        ->where(['status' => 2])
                                        ->sum('cash');

                                    // 根据支付类型，统计对应的费率金额
                                    $balance_cash = strval(1 - $type_value) * $type_finish_cashs;
                                    $balance_cash_array[$type_key] = $balance_cash ? $balance_cash / 100 : 0;
                                    $merchant_balance_cash = $merchant_balance_cash + $balance_cash;

                                    $payment_type_cash_count[$type_key]['all']['cash'] = $type_all_cashs ? $type_all_cashs / 100 : 0;
                                    $payment_type_cash_count[$type_key]['all']['count'] = $type_all_counts;
                                    $payment_type_cash_count[$type_key]['finish']['cash'] = $type_finish_cashs ? $type_finish_cashs / 100 : 0;
                                    $payment_type_cash_count[$type_key]['finish']['count'] = $type_finish_counts;
                                }

                                // 商户之前的余额
                                $payment_cash_table = Db::name('payment_cash')
                                    ->where(['merchant_id' => $single['id']])
                                    ->find();

                                $data['merchant_id'] = $single['id'];                                        // 商户号
                                $data['payment_type_cash_count'] = json_encode($payment_type_cash_count);    // 支付类型金额和数量json格式
                                $data['payment_type_rate'] = $single['payment_type_rate'];                   // 支付类型费率
                                $data['payment_type_balance_cash'] = json_encode($balance_cash_array);       // 支付类型结算金额json格式
                                $data['app_id'] = json_encode($app_id);                                      // 充值的订单包括哪些应用ID
                                $data['all_cash'] = $all_cashs;                                              // 创建订单金额
                                $data['finish_cash'] = $finish_cashs;                                        // 完成订单金额
                                $data['all_cash_count'] = $all_cash_counts;                                  // 创建订单数量
                                $data['finish_cash_count'] = $finish_cash_counts;                            // 完成订单数量
                                $data['balance_cash'] = ceil(strval($merchant_balance_cash));                // 结算金额
                                $data['poundage'] = $data['finish_cash'] - $data['balance_cash'];            // 手续费
                                $data['before_cash'] = isset($payment_cash_table['cash']) ? $payment_cash_table['cash'] : 0;  // 统计之前的余额
                                $data['trade_type'] = 'consumption';                                         // 交易类型
                                $data['dates'] = $statistics_date . ' 05:00:00';                             // 统计日期
                                $data['settlement_type'] = $single['settlement_type'];                       // 结算类型T是0，D是1
                                $data['settlement_day'] = $single['settlement_day'];                         // 结算天数
                                $data['status'] = $single['status'];                                         // 状态
                                $data['create_time'] = time();                                               // 创建时间
                                $data['update_time'] = time();                                               // 更新时间
                                $data['merchant_config'] = json_encode($single);                             // 商户号配置
                                $data['order_id'] = date('ymdHis', strtotime($data['dates'])) . random(8);   // 平台订单号
                                // 商户金额来源统计表
                                try {
                                    Db::name('payment_recharge_cash_source')
                                        ->insert($data);

                                    // 存在商户充值余额表
                                    if ($payment_cash_table) {

                                        // 商户配置开启
                                        if ($single['status'] == 1) {

                                            // 不是D0就执行
                                            if ($single['settlement_type'] == 0 || $single['settlement_day'] > 0) {
                                                try {
                                                    // 是否开启每天自动审核金额
                                                    if ($single['automatic_audit'] == 1) {
                                                        Db::name('payment_cash')
                                                            ->where(['merchant_id' => $single['id']])
                                                            ->inc('cash', $data['balance_cash'])                 // 剩余余额
                                                            ->inc('sum_cash', $data['balance_cash'])             // 总金额
                                                            ->inc('count', 1)                                    // 来源总次数
                                                            ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                                    } else {
                                                        Db::name('payment_cash')
                                                            ->where(['merchant_id' => $single['id']])
                                                            ->inc('transit_cash', $data['balance_cash'])         // 过渡金额
                                                            ->inc('count', 1)                                    // 来源总次数
                                                            ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                                    }
                                                } catch (\Exception $e) {
                                                    payment_error_log(710004, '商户钱包更新数据失败' . json_encode($cash_table), $e->getMessage());
                                                }
                                            }
                                        }
                                    } else {
                                        $cash_table['merchant_id'] = $data['merchant_id'];                   // 商户号
                                        $cash_table['cash'] = 0;                                             // 商户现金余额
                                        $cash_table['sum_cash'] = 0;                                         // 商户总现金
                                        $cash_table['freeze_cash'] = 0;                                      // 冻结金额
                                        $cash_table['transit_cash'] = $data['balance_cash'];                 // 过渡金额
                                        $cash_table['count'] = 1;                                            // 来源总次数
                                        $cash_table['withdrawal_sum_cash'] = 0;                              // 商户提现总金额
                                        $cash_table['withdrawal_count'] = 0;                                 // 提现总次数
                                        $cash_table['status'] = $single['status'];                           // 状态：0禁用：1启用
                                        $cash_table['dates'] = $data['dates'];                               // 上次统计时间
                                        $cash_table['create_time'] = strtotime($statistics_date);            // 创建时间
                                        $cash_table['update_time'] = time();                                 // 更新时间

                                        if ($single['status'] == 1) {

                                            // 不是D0就执行
                                            if ($single['settlement_type'] == 0 || $single['settlement_day'] > 0) {
                                                try {
                                                    Db::name('payment_cash')
                                                        ->insert($cash_table);
                                                } catch (\Exception $e) {
                                                    payment_error_log(710005, '商户钱包插入数据失败' . json_encode($cash_table), $e->getMessage());
                                                }
                                            }
                                        }
                                    }

                                    // 处理代理返利：开始
                                    $this->agentRebate($single, $data);
                                    $this->agentPayCompanyRebate($single, $data);
                                    $this->agentPaidCompanyRebate($single, $data);
                                    // 处理代理返利：结束
                                } catch (\Exception $e) {

                                    // 商户每天来源订单数据
                                    payment_error_log(710003, '商户插入每天来源订单数据失败', $data);
                                }
                            } else {

                                // 商户号支付类型费率配置有误
                                payment_error_log(710002, "商户号支付类型费率配置有误{$statistics_date}", $single);
                            }
                        } else {

                            // 已经存在
                            payment_error_log(710001, "商户号已经跑过指定日期数据{$statistics_date}", $single);
                        }

                        unset($single);
                    }
                }, 'id', 'desc');

            debug('end');
            payment_error_log(710006, debug('begin', 'end', 2), debug('begin', 'end', 'm'));
        } catch (\Exception $e) {
            payment_error_log(710000, $e->getMessage());
            return ['code' => 999, 'msg' => '404'];
        }
    }

    /**
     * 每天统计一次代理商户返利
     * @access protected 
     * @param  array   $single  商户配置
     * @param  array   $data    商户数据
     * @return boolean
     */
    protected function agentRebate($single = [], $data = [])
    {
        try {
            if ($data) {
                // 统计时间数据
                $statistics_date = date('Y-m-d', strtotime($data['dates']));

                // 是否存在开启的代理，处理代理返利
                if (strlen($single['sup_merchant']) == 8 && $single['status'] == 1 && $single['sup_merchant'] != $single['id'] && $data['balance_cash'] > 0) {
                    // 存在跳过
                    $exist_payment_agent_cash_source = Db::name('payment_agent_cash_source')
                        ->where(['merchant_id' => $single['id']])
                        ->whereTime('dates', 'between', ["{$statistics_date} 00:00:00", "{$statistics_date} 23:59:59"])
                        ->find();

                    if (!$exist_payment_agent_cash_source) {
                        $payment_type_cash_count_array = json_decode($data['payment_type_cash_count'], true);
                        // 支付类型对应的完成金额
                        foreach ($payment_type_cash_count_array as $payment_type_cash_count_key => $payment_type_cash_count_value) {
                            $payment_type_balance_cash_array[$payment_type_cash_count_key] = $payment_type_cash_count_value['finish']['cash'];
                        }

                        $agent_data = [];                                                                 // 代理金额来源统计表数据
                        $agent_balance_cash = 0;                                                          // 代理结算金额
                        $agent_balance_cash_array = [];                                                   // 代理根据支付类型，统计对应的费率金额
                        $agent_data['order_id'] = date('ymdHis', strtotime($data['dates'])) . random(8);  // 平台订单号
                        $agent_data['source_order_id'] = $data['order_id'];                               // 来源订单号
                        $agent_data['merchant_id'] = $data['merchant_id'];                                // 充值商户号
                        $agent_data['source_merchant_id'] = $data['merchant_id'];                         // 间接商户号
                        $agent_data['agent_id'] = $single['sup_merchant'];                                // 代理商户号
                        $agent_data['payment_type_cash_count'] = $data['payment_type_cash_count'];        // 充值商户支付类型金额和数量json格式
                        $agent_data['payment_type_rate'] = $data['payment_type_rate'];                    // 充值商户支付类型费率
                        $agent_data['payment_type_balance_cash'] = $data['payment_type_balance_cash'];    // 充值商户支付类型结算金额json格式
                        $agent_data['source_agent_payment_type_rate'] = '';                               // 间接代理商户支付类型费率
                        $agent_data['source_agent_payment_type_balance_cash'] = '';                       // 间接代理商户支付类型结算金额json格式
                        $agent_data['balance_cash'] = $data['balance_cash'];                              // 充值商户结算金额
                        $agent_data['dates'] = $data['dates'];                                            // 充值商户统计日期
                        // 充值商户支付类型费率
                        $payment_type_rate_array = json_decode($data['payment_type_rate'], true);

                        // 第一层返利(代理配置信息)
                        $agent_info_one = Db::name('payment_merchant_config')
                            ->where(['id' => $single['sup_merchant']])
                            ->find();
                        if ($agent_info_one) {

                            // 代理支付类型对应类型费率
                            $agent_payment_type_rate_array = json_decode($agent_info_one['payment_type_rate'], true);

                            if (is_array($agent_payment_type_rate_array)) {
                                // 循环商户支付类型对应类型费率
                                foreach ($payment_type_rate_array as $type_key => $type_value) {

                                    // 存在代理对应类型费率
                                    if (isset($agent_payment_type_rate_array[$type_key])) {
                                        if ($agent_payment_type_rate_array[$type_key] < $type_value) {
                                            // 开始返利                                                                               
                                            $balance_cash = strval($type_value - $agent_payment_type_rate_array[$type_key]) * $payment_type_balance_cash_array[$type_key];
                                            $agent_balance_cash_array[$type_key] = $balance_cash ? $balance_cash : 0;
                                            $agent_balance_cash = $agent_balance_cash + $balance_cash;
                                        }
                                    }
                                }

                                $agent_data['agent_payment_type_balance_cash'] = json_encode($agent_balance_cash_array);    // 代理支付类型结算金额json格式
                                $agent_data['agent_payment_type_rate'] = $agent_info_one['payment_type_rate'];              // 代理支付类型费率    
                                $agent_data['agent_balance_cash'] = intval(strval($agent_balance_cash * 100));              // 代理结算金额
                                $agent_data['relation'] = 1;                                                                // 代理关联等级
                                $agent_data['settlement_type'] = $agent_info_one['settlement_type'];                        // 代理结算类型T是0，D是1
                                $agent_data['settlement_day'] = $agent_info_one['settlement_day'];                          // 代理结算天数
                                $agent_data['create_time'] = time();                                                        // 创建时间
                                $agent_data['update_time'] = time();                                                        // 更新时间  
                                $agent_data['trade_type'] = 'consumption';                                                  // 交易类型
                                $agent_data['merchant_config'] = json_encode($agent_info_one);                              // 商户号配置

                                $agent_payment_cash_table = Db::name('payment_cash')
                                    ->where(['merchant_id' => $agent_info_one['id']])
                                    ->find();
                                $agent_data['agent_before_cash'] = isset($agent_payment_cash_table['cash']) ? $agent_payment_cash_table['cash'] : 0;  // 统计代理之前的余额
                                // 是代理同时状态开启
                                if ($agent_info_one['status'] == 1 && $agent_info_one['agent_status'] == 1) {
                                    $agent_data['status'] = 1;
                                    try {
                                        Db::name('payment_agent_cash_source')
                                            ->insert($agent_data);

                                        // 处理代理钱包
                                        try {
                                            // 是否开启每天自动审核金额
                                            if ($agent_info_one['automatic_audit'] == 1) {
                                                Db::name('payment_cash')
                                                    ->where(['merchant_id' => $agent_info_one['id']])
                                                    ->inc('cash', $agent_data['agent_balance_cash'])                 // 剩余余额
                                                    ->inc('sum_cash', $agent_data['agent_balance_cash'])             // 总金额
                                                    ->inc('count', 1)                                                // 来源总次数
                                                    ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                            } else {
                                                Db::name('payment_cash')
                                                    ->where(['merchant_id' => $agent_info_one['id']])
                                                    ->inc('transit_cash', $agent_data['agent_balance_cash'])         // 过渡金额
                                                    ->inc('count', 1)                                                // 来源总次数
                                                    ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                            }

                                            // 第二层返利：开始
                                            // 是否存在开启的代理，处理代理返利
                                            if (strlen($agent_info_one['sup_merchant']) == 8 && $agent_info_one['status'] == 1 && $agent_info_one['sup_merchant'] != $agent_info_one['id'] && $agent_data['agent_balance_cash'] > 0) {

                                                $agent_balance_cash = 0;                                                          // 代理结算金额
                                                $agent_balance_cash_array = [];                                                   // 代理根据支付类型，统计对应的费率金额
                                                $agent_data['order_id'] = date('ymdHis', strtotime($data['dates'])) . random(8);  // 平台订单号
                                                $agent_data['source_order_id'] = $data['order_id'];                               // 间接订单号
                                                $agent_data['merchant_id'] = $data['merchant_id'];                                // 充值商户号
                                                $agent_data['source_merchant_id'] = $agent_info_one['id'];                        // 间接商户号
                                                $agent_data['agent_id'] = $agent_info_one['sup_merchant'];                        // 代理商户号
                                                $agent_data['payment_type_cash_count'] = $data['payment_type_cash_count'];        // 充值商户支付类型金额和数量json格式
                                                $agent_data['payment_type_rate'] = $data['payment_type_rate'];                    // 充值商户支付类型费率
                                                $agent_data['payment_type_balance_cash'] = $data['payment_type_balance_cash'];    // 充值商户支付类型结算金额json格式
                                                $agent_data['source_agent_payment_type_rate'] = $agent_data['agent_payment_type_rate'];                  // 间接商户支付类型费率
                                                $agent_data['source_agent_payment_type_balance_cash'] = $agent_data['agent_payment_type_balance_cash'];  // 间接商户支付类型结算金额json格式
                                                $agent_data['balance_cash'] = $data['balance_cash'];                              // 充值商户结算金额
                                                $agent_data['dates'] = $data['dates'];                                            // 充值商户统计日期
                                                // 上级代理费率
                                                $payment_type_rate_array = json_decode($agent_data['agent_payment_type_rate'], true);

                                                // 第二层返利(代理配置信息)
                                                $agent_info_two = Db::name('payment_merchant_config')
                                                    ->where(['id' => $agent_info_one['sup_merchant']])
                                                    ->find();
                                                if ($agent_info_two) {

                                                    // 代理支付类型对应类型费率
                                                    $agent_payment_type_rate_array = json_decode($agent_info_two['payment_type_rate'], true);

                                                    if (is_array($agent_payment_type_rate_array)) {
                                                        // 循环代理商户支付类型对应类型费率（代理）
                                                        foreach ($payment_type_rate_array as $type_key => $type_value) {

                                                            // 存在代理对应类型费率
                                                            if (isset($agent_payment_type_rate_array[$type_key])) {
                                                                if ($agent_payment_type_rate_array[$type_key] < $type_value) {
                                                                    // 开始返利                                                                               
                                                                    $balance_cash = strval($type_value - $agent_payment_type_rate_array[$type_key]) * $payment_type_balance_cash_array[$type_key];
                                                                    $agent_balance_cash_array[$type_key] = $balance_cash ? $balance_cash : 0;
                                                                    $agent_balance_cash = $agent_balance_cash + $balance_cash;
                                                                }
                                                            }
                                                        }
                                                        $agent_data['agent_payment_type_balance_cash'] = json_encode($agent_balance_cash_array);    // 代理支付类型结算金额json格式
                                                        $agent_data['agent_payment_type_rate'] = $agent_info_two['payment_type_rate'];              // 代理支付类型费率    
                                                        $agent_data['agent_balance_cash'] = intval(strval($agent_balance_cash * 100));              // 代理结算金额
                                                        $agent_data['relation'] = 2;                                                                // 代理关联等级
                                                        $agent_data['settlement_type'] = $agent_info_two['settlement_type'];                        // 代理结算类型T是0，D是1
                                                        $agent_data['settlement_day'] = $agent_info_two['settlement_day'];                          // 代理结算天数
                                                        $agent_data['create_time'] = time();                                                        // 创建时间
                                                        $agent_data['update_time'] = time();                                                        // 更新时间  
                                                        $agent_data['trade_type'] = 'consumption';                                                  // 交易类型
                                                        $agent_data['merchant_config'] = json_encode($agent_info_two);                              // 商户号配置

                                                        $agent_payment_cash_table = Db::name('payment_cash')
                                                            ->where(['merchant_id' => $agent_info_two['id']])
                                                            ->find();
                                                        $agent_data['agent_before_cash'] = isset($agent_payment_cash_table['cash']) ? $agent_payment_cash_table['cash'] : 0;  // 统计代理之前的余额
                                                        // 是代理同时状态开启
                                                        if ($agent_info_two['status'] == 1 && $agent_info_two['agent_status'] == 1) {
                                                            $agent_data['status'] = 1;
                                                            try {
                                                                Db::name('payment_agent_cash_source')
                                                                    ->insert($agent_data);

                                                                // 处理代理钱包
                                                                try {
                                                                    // 是否开启每天自动审核金额
                                                                    if ($agent_info_two['automatic_audit'] == 1) {
                                                                        Db::name('payment_cash')
                                                                            ->where(['merchant_id' => $agent_info_two['id']])
                                                                            ->inc('cash', $agent_data['agent_balance_cash'])                 // 剩余余额
                                                                            ->inc('sum_cash', $agent_data['agent_balance_cash'])             // 总金额
                                                                            ->inc('count', 1)                                                // 来源总次数
                                                                            ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                                                    } else {
                                                                        Db::name('payment_cash')
                                                                            ->where(['merchant_id' => $agent_info_two['id']])
                                                                            ->inc('transit_cash', $agent_data['agent_balance_cash'])         // 过渡金额
                                                                            ->inc('count', 1)                                                // 来源总次数
                                                                            ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                                                    }

                                                                    if ($agent_data['agent_balance_cash'] > 0) {
                                                                        // 第三层返利：开始
                                                                        // 
                                                                        // 第三层返利：结束
                                                                    }
                                                                } catch (\Exception $e) {
                                                                    payment_error_log(720009, '第二层代理钱包更新数据失败' . json_encode($agent_data), $e->getMessage());
                                                                }
                                                            } catch (\Exception $e) {

                                                                // 代理每天来源订单数据
                                                                payment_error_log(720008, '第二层代理插入每天来源订单数据失败', $agent_data);
                                                            }
                                                        } else {
                                                            // 不是代理或者被禁用
                                                            $agent_data['status'] = 0;
                                                            try {
                                                                Db::name('payment_agent_cash_source')
                                                                    ->insert($agent_data);
                                                            } catch (\Exception $e) {

                                                                // 代理每天来源订单数据
                                                                payment_error_log(720007, '第二层代理插入每天来源订单数据失败', $data);
                                                            }
                                                        }
                                                    } else {

                                                        // 代理支付类型费率配置有误
                                                        payment_error_log(720006, "第二层代理支付类型费率配置有误{$statistics_date}", $single);
                                                    }
                                                }

                                                // 第二层返利：结束
                                            }
                                        } catch (\Exception $e) {
                                            payment_error_log(720005, '第一层代理钱包更新数据失败' . json_encode($agent_data), $e->getMessage());
                                        }
                                    } catch (\Exception $e) {

                                        // 代理每天来源订单数据
                                        payment_error_log(720004, '第一层代理插入每天来源订单数据失败', $agent_data);
                                    }
                                } else {
                                    // 不是代理或者被禁用
                                    $agent_data['status'] = 0;
                                    try {
                                        Db::name('payment_agent_cash_source')
                                            ->insert($agent_data);
                                    } catch (\Exception $e) {

                                        // 代理每天来源订单数据
                                        payment_error_log(720003, '第一层代理插入每天来源订单数据失败', $data);
                                    }
                                }
                            } else {

                                // 代理支付类型费率配置有误
                                payment_error_log(720002, "第一层代理支付类型费率配置有误{$statistics_date}", $single);
                            }
                        }
                    } else {

                        // 已经存在
                        payment_error_log(720001, "代理返利已经跑过指定日期数据{$statistics_date}", $single);
                    }
                }
            }
        } catch (\Exception $e) {
            payment_error_log(720000, $e->getMessage());
            return ['code' => 999, 'msg' => '404'];
        }
    }

    /**
     * 每天统计一次代理支付通道返利
     * @access protected 
     * @param  array   $single        商户配置
     * @param  array   $data_array    商户数据
     * @return boolean
     */
    protected function agentPayCompanyRebate($single = [], $data_array = [])
    {
        try {
            if ($data_array) {
                $statistics_date = date('Y-m-d', strtotime($data_array['dates']));

                $data = [];                          // 商户金额来源统计表数据
                $merchant_balance_cash = 0;          // 结算金额
                $type_all_cashs = 0;                 // 支付类型对应金额
                $type_all_counts = 0;                // 支付类型对应数量
                $type_finish_cashs = 0;              // 支付类型对应完成金额
                $type_finish_counts = 0;             // 支付类型对应完成数量
                $cash_table = [];                    // 商户钱包表数据
                $payment_type_cash_count = [];       // 通道类型金额和数量json格式
                $agent_company_rate_arrays = [];     // 代理通道费率json格式
                $payment_company_rate_arrays = [];   // 支付通道配置费率json格式
                $company_type_balance_cash = [];     // 通道对应支付类型结算金额json格式
                $agent_company_balance_cash = [];    // 代理通道对应结算金额json格式
                // 是否存在开启的代理，处理代理返利
                if ($single['status'] == 1 && $single['agent_status'] == 1) {
                    // 存在跳过
                    $exist_payment_company_agent_cash_source = Db::name('payment_agent_company_cash_source')
                        ->where(['merchant_id' => $single['id']])
                        ->whereTime('dates', 'between', ["{$statistics_date} 00:00:00", "{$statistics_date} 23:59:59"])
                        ->find();

                    if (!$exist_payment_company_agent_cash_source) {

                        // 代理支付通道
                        $payment_agent_companys = Db::name('payment_agent_company')
                            ->where(['merchant_id' => $single['id']])
                            ->where(['status' => 1])
                            ->column('company_name');

                        if ($payment_agent_companys) {

                            // 循环支付通道
                            foreach ($payment_agent_companys as $payment_agent_company_value) {
                                // 代理通道费率
                                $agent_company_rate = Db::name('payment_agent_company')
                                    ->where(['merchant_id' => $single['id']])
                                    ->where(['company_name' => $payment_agent_company_value])
                                    ->value('payment_type_rate');
                                $agent_company_rate_arrays[$payment_agent_company_value] = $agent_company_rate;
                                $agent_company_rate_array = json_decode($agent_company_rate, true);

                                // 支付通道费率
                                $payment_company_rate = Db::name('payment_pay_company')
                                    ->where(['name' => $payment_agent_company_value])
                                    ->value('payment_type_rate');
                                $payment_company_rate_arrays[$payment_agent_company_value] = $payment_company_rate;
                                $payment_company_rate_array = json_decode($payment_company_rate, true);

                                $temp_map = [];
                                // 用支付完成时间统计，不会掉单后，第二天处理钱少
                                $temp_map[] = ['update_time', ['>=', strtotime($statistics_date)], ['<', strtotime($statistics_date) + 86400]];

                                $temp_map[] = ['child_company', '=', $payment_agent_company_value];

                                // 记录充值的支付类型
                                $all_type_array = Db::name('payment_order')
                                    ->where($temp_map)
                                    ->distinct(true)
                                    ->column('type');

                                if ($all_type_array) {
                                    $company_balance_cash = 0;

                                    foreach ($all_type_array as $type_key) {

                                        // 支付类型对应创建数量
                                        $type_all_counts = Db::name('payment_order')
                                            ->where($temp_map)
                                            ->where(['type' => $type_key])
                                            ->count();

                                        // 支付类型对应完成数量
                                        $type_finish_counts = Db::name('payment_order')
                                            ->where($temp_map)
                                            ->where(['type' => $type_key])
                                            ->where(['status' => 2])
                                            ->count();

                                        // 支付类型对应创建金额
                                        $type_all_cashs = Db::name('payment_order')
                                            ->where($temp_map)
                                            ->where(['type' => $type_key])
                                            ->sum('cash');

                                        // 支付类型对应完成金额
                                        $type_finish_cashs = Db::name('payment_order')
                                            ->where($temp_map)
                                            ->where(['type' => $type_key])
                                            ->where(['status' => 2])
                                            ->sum('cash');

                                        // 根据支付类型，统计对应的费率金额
                                        $rate = strval($agent_company_rate_array[$type_key] - $payment_company_rate_array[$type_key]);
                                        $rates = $rate > 0 ? $rate : 0;
                                        $balance_cash = $rates * $type_finish_cashs;
                                        $company_type_balance_cash[$payment_agent_company_value][$type_key] = $balance_cash ? $balance_cash / 100 : 0;
                                        $merchant_balance_cash = $merchant_balance_cash + $balance_cash;
                                        // 通道对应结算金额
                                        $company_balance_cash = $company_balance_cash + $balance_cash;

                                        $payment_type_cash_count[$payment_agent_company_value][$type_key]['all']['cash'] = $type_all_cashs ? $type_all_cashs / 100 : 0;
                                        $payment_type_cash_count[$payment_agent_company_value][$type_key]['all']['count'] = $type_all_counts;
                                        $payment_type_cash_count[$payment_agent_company_value][$type_key]['finish']['cash'] = $type_finish_cashs ? $type_finish_cashs / 100 : 0;
                                        $payment_type_cash_count[$payment_agent_company_value][$type_key]['finish']['count'] = $type_finish_counts;
                                    }

                                    $agent_company_balance_cash[$payment_agent_company_value] = $company_balance_cash ? $company_balance_cash / 100 : 0;
                                }
                            }
                            // 商户之前的余额
                            $payment_cash_table = Db::name('payment_cash')
                                ->where(['merchant_id' => $single['id']])
                                ->find();

                            $data['merchant_id'] = $single['id'];                                            // 商户号
                            $data['payment_type_cash_count'] = json_encode($payment_type_cash_count);        // 通道类型金额和数量json格式
                            $data['agent_company_rate'] = json_encode($agent_company_rate_arrays);           // 代理通道费率json格式
                            $data['payment_company_rate'] = json_encode($payment_company_rate_arrays);       // 支付通道配置费率json格式
                            $data['company_type_balance_cash'] = json_encode($company_type_balance_cash);    // 通道对应支付类型结算金额json格式
                            $data['agent_company_balance_cash'] = json_encode($agent_company_balance_cash);  // 代理通道对应结算金额json格式
                            $data['balance_cash'] = intval(strval($merchant_balance_cash));                  // 结算金额
                            $data['before_cash'] = isset($payment_cash_table['cash']) ? $payment_cash_table['cash'] : 0;  // 统计之前的余额
                            $data['trade_type'] = 'consumption';                                             // 交易类型
                            $data['dates'] = $statistics_date . ' 05:00:00';                                 // 统计日期
                            $data['settlement_type'] = $single['settlement_type'];                           // 结算类型T是0，D是1
                            $data['settlement_day'] = $single['settlement_day'];                             // 结算天数
                            $data['status'] = $single['status'];                                             // 状态
                            $data['create_time'] = time();                                                   // 创建时间
                            $data['update_time'] = time();                                                   // 更新时间
                            $data['merchant_config'] = json_encode($single);                                 // 商户号配置
                            $data['order_id'] = date('ymdHis', strtotime($data['dates'])) . random(8);       // 平台订单号
                            // 商户金额来源统计表
                            try {
                                Db::name('payment_agent_company_cash_source')
                                    ->insert($data);

                                // 存在商户充值余额表
                                if ($payment_cash_table) {

                                    // 商户配置开启
                                    if ($single['status'] == 1) {

                                        try {
                                            // 是否开启每天自动审核金额
                                            if ($single['automatic_audit'] == 1) {
                                                Db::name('payment_cash')
                                                    ->where(['merchant_id' => $single['id']])
                                                    ->inc('cash', $data['balance_cash'])                 // 剩余余额
                                                    ->inc('sum_cash', $data['balance_cash'])             // 总金额
                                                    ->inc('count', 1)                                    // 来源总次数
                                                    ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                            } else {
                                                Db::name('payment_cash')
                                                    ->where(['merchant_id' => $single['id']])
                                                    ->inc('transit_cash', $data['balance_cash'])         // 过渡金额
                                                    ->inc('count', 1)                                    // 来源总次数
                                                    ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                            }
                                        } catch (\Exception $e) {
                                            payment_error_log(730004, '商户钱包更新数据失败' . json_encode($cash_table), $e->getMessage());
                                        }
                                    }
                                } else {
                                    $cash_table['merchant_id'] = $data['merchant_id'];                   // 商户号
                                    $cash_table['cash'] = 0;                                             // 商户现金余额
                                    $cash_table['sum_cash'] = 0;                                         // 商户总现金
                                    $cash_table['freeze_cash'] = 0;                                      // 冻结金额
                                    $cash_table['transit_cash'] = $data['balance_cash'];                 // 过渡金额
                                    $cash_table['count'] = 1;                                            // 来源总次数
                                    $cash_table['withdrawal_sum_cash'] = 0;                              // 商户提现总金额
                                    $cash_table['withdrawal_count'] = 0;                                 // 提现总次数
                                    $cash_table['status'] = $single['status'];                           // 状态：0禁用：1启用
                                    $cash_table['dates'] = $data['dates'];                               // 上次统计时间
                                    $cash_table['create_time'] = strtotime($statistics_date);            // 创建时间
                                    $cash_table['update_time'] = time();                                 // 更新时间

                                    if ($single['status'] == 1) {

                                        try {
                                            Db::name('payment_cash')
                                                ->insert($cash_table);
                                        } catch (\Exception $e) {
                                            payment_error_log(730005, '商户钱包插入数据失败' . json_encode($cash_table), $e->getMessage());
                                        }
                                    }
                                }
                            } catch (\Exception $e) {

                                // 商户每天来源订单数据
                                payment_error_log(730003, '商户插入每天代理通道返利数据失败', $data);
                            }
                        } else {

                            // 代理通道没有配置
                            // payment_error_log(730002, "代理通道没有配置{$statistics_date}", $single);
                        }
                    } else {

                        // 已经存在
                        payment_error_log(730001, "代理通道返利已经跑过指定日期数据{$statistics_date}", $single);
                    }
                }
            }
        } catch (\Exception $e) {
            payment_error_log(730000, $e->getMessage());
            return ['code' => 999, 'msg' => '404'];
        }
    }

    /**
     * 每天统计一次代理代付通道返利
     * @access protected 
     * @param  array   $single        商户配置
     * @param  array   $data_array    商户数据
     * @return boolean
     */
    protected function agentPaidCompanyRebate($single = [], $data_array = [])
    {
        try {
            if ($data_array) {
                $statistics_date = date('Y-m-d', strtotime($data_array['dates']));

                $data = [];                          // 商户金额来源统计表数据
                $merchant_balance_cash = 0;          // 结算金额
                $cash_table = [];                    // 商户钱包表数据
                $agent_company_data_config = [];     // 代理代付通道配置
                $paid_company_data_config = [];      // 代付通道配置
                $paid_cash_count = [];               // 代付通道金额和数量
                // 是否存在开启的代理，处理代理返利
                if ($single['status'] == 1 && $single['agent_status'] == 1) {
                    // 存在跳过
                    $exist_paid_company_agent_cash_source = Db::name('payment_agent_paid_company_cash_source')
                        ->where(['merchant_id' => $single['id']])
                        ->whereTime('dates', 'between', ["{$statistics_date} 00:00:00", "{$statistics_date} 23:59:59"])
                        ->find();

                    if (!$exist_paid_company_agent_cash_source) {

                        // 代理代付通道
                        $paid_agent_companys = Db::name('payment_agent_paid_company')
                            ->where(['merchant_id' => $single['id']])
                            ->where(['status' => 1])
                            ->column('company_name');

                        if ($paid_agent_companys) {

                            // 循环代付通道
                            foreach ($paid_agent_companys as $paid_agent_company_value) {
                                // 代理价格
                                $agent_company_config = Db::name('payment_agent_paid_company')
                                    ->where(['merchant_id' => $single['id']])
                                    ->where(['company_name' => $paid_agent_company_value])
                                    ->find();
                                $paid_start_price = $agent_company_config['paid_start_price'];
                                $paid_rate = $agent_company_config['paid_rate'];

                                // 通道价格
                                $paid_company_config = Db::name('payment_paid_company')
                                    ->where(['name' => $paid_agent_company_value])
                                    ->find();
                                $company_paid_start_price = $paid_company_config['paid_start_price'];
                                $company_paid_rate = $paid_company_config['paid_rate'];

                                $temp_map = [];
                                // 用代付完成时间统计，不会掉单后，第二天处理钱少
                                $temp_map[] = ['update_time', ['>=', strtotime($statistics_date)], ['<', strtotime($statistics_date) + 86400]];

                                $temp_map[] = ['child_company', '=', $paid_agent_company_value];

                                // 银行卡代付
                                if ($paid_company_config['paid_class'] == 0) {
                                    $order_paid_counts = Db::name('payment_order_paid')
                                        ->where($temp_map)
                                        ->where(['status' => 2])
                                        ->count();
                                    $order_paid_cashs = Db::name('payment_order_paid')
                                        ->where($temp_map)
                                        ->where(['status' => 2])
                                        ->sum('cash');
                                }
                                // 支付宝代付
                                if ($paid_company_config['paid_class'] == 1) {
                                    $order_paid_counts = Db::name('payment_order_alipay_paid')
                                        ->where($temp_map)
                                        ->where(['status' => 2])
                                        ->count();
                                    $order_paid_cashs = Db::name('payment_order_alipay_paid')
                                        ->where($temp_map)
                                        ->where(['status' => 2])
                                        ->sum('cash');
                                }

                                $balance_cash = strval($paid_start_price - $company_paid_start_price) * $order_paid_counts * 100 + strval($paid_rate - $company_paid_rate) * $order_paid_cashs;
                                $balance_cash = $balance_cash > 0 ? $balance_cash : 0;
                                $merchant_balance_cash = $merchant_balance_cash + $balance_cash;

                                $agent_company_data_config[$single['id']][$paid_agent_company_value] = $agent_company_config;
                                $paid_company_data_config[$paid_agent_company_value] = $paid_company_config;

                                $paid_cash_count[$paid_agent_company_value]['cash'] = $order_paid_cashs ? $order_paid_cashs / 100 : 0;
                                $paid_cash_count[$paid_agent_company_value]['count'] = $order_paid_counts;
                            }
                            // 商户之前的余额
                            $payment_cash_table = Db::name('payment_cash')
                                ->where(['merchant_id' => $single['id']])
                                ->find();

                            $data['merchant_id'] = $single['id'];                                            // 商户号
                            $data['agent_company'] = json_encode($agent_company_data_config);                // 代理代付通道配置
                            $data['paid_company'] = json_encode($paid_company_data_config);                  // 代付通道配置
                            $data['paid_cash_count'] = json_encode($paid_cash_count);                        // 代付通道金额和数量
                            $data['balance_cash'] = intval(strval($merchant_balance_cash));                  // 结算金额
                            $data['before_cash'] = isset($payment_cash_table['cash']) ? $payment_cash_table['cash'] : 0;  // 统计之前的余额
                            $data['trade_type'] = 'paid';                                                    // 交易类型
                            $data['dates'] = $statistics_date . ' 05:00:00';                                 // 统计日期
                            $data['settlement_type'] = $single['settlement_type'];                           // 结算类型T是0，D是1
                            $data['settlement_day'] = $single['settlement_day'];                             // 结算天数
                            $data['status'] = $single['status'];                                             // 状态
                            $data['create_time'] = time();                                                   // 创建时间
                            $data['update_time'] = time();                                                   // 更新时间
                            $data['merchant_config'] = json_encode($single);                                 // 商户号配置
                            $data['order_id'] = date('ymdHis', strtotime($data['dates'])) . random(8);       // 平台订单号
                            // 商户金额来源统计表
                            try {
                                Db::name('payment_agent_paid_company_cash_source')
                                    ->insert($data);

                                // 存在商户充值余额表
                                if ($payment_cash_table) {

                                    // 商户配置开启
                                    if ($single['status'] == 1) {

                                        try {
                                            // 是否开启每天自动审核金额
                                            if ($single['automatic_audit'] == 1) {
                                                Db::name('payment_cash')
                                                    ->where(['merchant_id' => $single['id']])
                                                    ->inc('cash', $data['balance_cash'])                 // 剩余余额
                                                    ->inc('sum_cash', $data['balance_cash'])             // 总金额
                                                    ->inc('count', 1)                                    // 来源总次数
                                                    ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                            } else {
                                                Db::name('payment_cash')
                                                    ->where(['merchant_id' => $single['id']])
                                                    ->inc('transit_cash', $data['balance_cash'])         // 过渡金额
                                                    ->inc('count', 1)                                    // 来源总次数
                                                    ->update(['dates' => $data['dates'], 'update_time' => time()]);
                                            }
                                        } catch (\Exception $e) {
                                            payment_error_log(740004, '商户钱包更新数据失败' . json_encode($cash_table), $e->getMessage());
                                        }
                                    }
                                } else {
                                    $cash_table['merchant_id'] = $data['merchant_id'];                   // 商户号
                                    $cash_table['cash'] = 0;                                             // 商户现金余额
                                    $cash_table['sum_cash'] = 0;                                         // 商户总现金
                                    $cash_table['freeze_cash'] = 0;                                      // 冻结金额
                                    $cash_table['transit_cash'] = $data['balance_cash'];                 // 过渡金额
                                    $cash_table['count'] = 1;                                            // 来源总次数
                                    $cash_table['withdrawal_sum_cash'] = 0;                              // 商户提现总金额
                                    $cash_table['withdrawal_count'] = 0;                                 // 提现总次数
                                    $cash_table['status'] = $single['status'];                           // 状态：0禁用：1启用
                                    $cash_table['dates'] = $data['dates'];                               // 上次统计时间
                                    $cash_table['create_time'] = strtotime($statistics_date);            // 创建时间
                                    $cash_table['update_time'] = time();                                 // 更新时间

                                    if ($single['status'] == 1) {

                                        try {
                                            Db::name('payment_cash')
                                                ->insert($cash_table);
                                        } catch (\Exception $e) {
                                            payment_error_log(740005, '商户钱包插入数据失败' . json_encode($cash_table), $e->getMessage());
                                        }
                                    }
                                }
                            } catch (\Exception $e) {

                                // 商户每天来源订单数据
                                payment_error_log(740003, '商户插入每天代理代付通道返利数据失败', $data);
                            }
                        } else {

                            // 代理代付通道没有配置
                            // payment_error_log(740002, "代理代付通道没有配置{$statistics_date}", $single);
                        }
                    } else {

                        // 已经存在
                        payment_error_log(740001, "代理代付通道返利已经跑过指定日期数据{$statistics_date}", $single);
                    }
                }
            }
        } catch (\Exception $e) {
            payment_error_log(740000, $e->getMessage());
            return ['code' => 999, 'msg' => '404'];
        }
    }
}
